import router from './router'

import { asyncRoutes } from '@/router'

import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' 
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
    if (to.name == "Home") {
      store.dispatch('app/toggleNavbarEle', false)
    } else {
      store.dispatch('app/toggleNavbarEle', true)
    }
    // start progress bar
    NProgress.start()
  
    // set page title
    document.title = getPageTitle(to.meta.title)
  
    // determine whether the user has logged in
    const hasToken = getToken()
    if (hasToken) {
      if (to.path === '/login') {
        next()
        NProgress.done()
      }else if(to.path === '/oidc-callback'){
        next()
        NProgress.done()
      }else if(to.path === '/oidc-silent-renew'){
        next()
        NProgress.done()
      } else {
        const userInfo = store.getters.userInfo
        if (userInfo.profile) {
          const accessRoutes = await store.dispatch('permission/generateRoutes', userInfo)
          router.addRoutes(accessRoutes)
          next()
        } else {
          try {
            // get user info
            const userInfo = await store.dispatch('userService/getUser')
            if(userInfo && userInfo.profile){
               // generate accessible routes map based on roles
              const accessRoutes = await store.dispatch('permission/generateRoutes', userInfo)
              // dynamically add accessible routes
              router.addRoutes(accessRoutes)
            }
            // hack method to ensure that addRoutes is complete
            // set the replace: true, so the navigation will not leave a history record
            //next({ ...to, replace: true })
            next()
          } catch (error) {
            // remove token and go to login page to re-login
            alert(error)
            //await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login`)
            NProgress.done()
          }
        }
      }
    } else {
      /* has no token*/
      // test no permission - by jerry liu
      // if (whiteList.indexOf(to.path) === -1) {
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        //next(`/login?redirect=${to.path}`)
        next()
        NProgress.done()
      }
    }
  })
  
  router.afterEach(() => {
    // finish progress bar
    NProgress.done()
  })